import tpl from './tpl/wrapper.tpl';
import itemTpl from './tpl/item.tpl';
import controlTpl from './tpl/control.tpl';
import indicatorTpl from './tpl/indicator.tpl'
import './index.scss';
import tools from '../../utils/tools';

class Carousel {
  constructor(el, swiperDatas) {
    this.name = 'carousel';
    this.$el = el;
    this.swiperDatas = swiperDatas;
    this.swiperLen = this.swiperDatas.length;
    this.curIdx = 0;
  }
  async init () {
    await this.render();
    this.bindEvent();
    this.autoPlay()
  }
  async render () {
    await this.$el.append(tools.tplReplace(tpl(), {
      list: this.renderList(this.swiperDatas),
      indicator: this.renderIndicator(),
      control: controlTpl(),
      indicatorW: 18 * this.swiperLen
    }));
    this.$carousel = $('.J_carousel');
    this.$carItem = this.$carousel.find('.car-item');
    this.$carIndicators = this.$carousel.find('.indicator-item');
  }
  renderList (data) {
    var list = '';
    data.forEach((item, idx) => {
      list += tools.tplReplace(itemTpl(), {
        swiper_img: item.pic,
        alt: item.alt,
        isActive: idx === 0 ? 'active' : ''
      })
    })
    return list;
  }
  renderIndicator () {
    let list = '';
    for(var i = 0; i < this.swiperLen; i++) {
      list += tools.tplReplace(indicatorTpl(), {
        isCurrent: i === 0 ? 'current' : ''
      })
    }
    return list;
  }
  bindEvent () {
    this.$carousel.on('click', $.proxy(this.carouselClick, this));
    this.$carousel.on('mouseenter', $.proxy(this.mouseInOut, this));
    this.$carousel.on('mouseleave', $.proxy(this.mouseInOut, this));
  }
  carouselClick (e) {
    const tar = e.target,
          className = tools.trimSpace(tar.className),
          $tar = $(tar)
    switch (className) {
      case 'indicator-item':
        this.curIdx = $tar.index();
        this.fadeAction(this.curIdx);
        break;
      case 'car-control':
        this.run($tar.attr('data-dir'))
        break;
      default: 
        break;
    }
  }
  mouseInOut (e) {
    switch (e.type) {
      case 'mouseenter':
        clearInterval(Carousel.timer);
        break;
      case 'mouseleave':
        this.autoPlay();
        break;
      default:
        break;
    }
  }
  run (dir) {
    switch (dir) {
      case 'prev': 
        if(this.curIdx === 0) {
          this.curIdx = this.swiperLen - 1;
        } else {
          this.curIdx--;
        }
        break;
      case 'next':
        if(this.curIdx >= this.swiperLen - 1) {
          this.curIdx = 0
        } else {
          this.curIdx++
        }
        break;
      default:
        break;
    }
    this.fadeAction(this.curIdx);
  }
  fadeAction (index) {
    this.$carItem.eq(index).fadeIn().siblings().fadeOut();
    this.$carIndicators.eq(index).addClass('current').siblings().removeClass('current');
  }
  autoPlay () {
    // 需要注意this的指向问题
    Carousel.timer = setInterval($.proxy(this.run.bind(this, 'next'), this), 3000);
  }
}
export { Carousel }